package edu.ynu.se.xiecheng.achitectureclass.project.interceptor;

import edu.ynu.se.xiecheng.achitectureclass.project.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        // 处理OPTIONS请求
        if (req.getMethod().equals("OPTIONS")) {
            resp.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        // 获取请求url
        String url = req.getRequestURL().toString();
        log.info("请求的url: {}", url);

        // 排除根路径 "/" 的请求
        if (url.equals("http://localhost:8080/")) {
            log.info("访问根路径, 放行...");
            return true;
        }

        // 如果是登录请求，直接放行
        if (url.contains("/login") || url.contains("/register") || url.contains("/user/login") || url.contains("/user/register")) {
            log.info("登录或注册操作, 放行...");
            return true;
        }

        if (url.contains("doc.html") || url.contains("swagger-resources") || url.contains("v2/api-docs")|| url.contains("webjars")){
            return true;
        }

        // 获取请求头中的 Authorization 字段
        String authHeader = req.getHeader("Authorization");
//        log.info("Authorization header: {}", authHeader);

        // 判断 Authorization 请求头是否存在，且格式是否正确
        if (!StringUtils.hasLength(authHeader) || !authHeader.startsWith("Bearer ")) {
            log.info("Authorization 请求头为空或格式不正确, 返回未登录的信息");
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write("{\"error\":\"Unauthorized: Please login\"}");
            return false;
        }

        String jwt = authHeader.substring(7);
//        log.info("JWT token: {}", jwt);

        try {
            JwtUtils.parseJWT(jwt);
            log.info("令牌合法, 放行");
            return true;
        } catch (Exception e) {
            log.error("解析令牌失败", e);
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write("{\"error\":\"Invalid token\"}");
            return false;
        }
    }
}
